package com.imooc.order.controller;


import com.imooc.product.client.ProductClient;
import com.imooc.product.common.DecreaseStockInput;
import com.imooc.product.common.ProductInfoOutput;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;

@RestController
@Slf4j
public class ClientController {

    @Autowired
    RestTemplate restTemplate;
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private ProductClient productClient;


    @GetMapping("/decreaseStock")

    public Object decreaseStock(){
        productClient.decreaseStock(Arrays.asList(new DecreaseStockInput("157875196366160022",3)));
        return "ok";
    }

    @GetMapping("/getProductList")
    public Object getProductList(){
        List<ProductInfoOutput> productInfoList = productClient.listForOrder(Arrays.asList("157875196366160022", "164103465734242707"));
        log.info("response is -> {}",productInfoList);
        return productInfoList;
    }





    /**
     * 第一种方式(直接使用 restTemplate url写死)
     * @return
     */
    @GetMapping("/getProductMsg1")
    public String getProductMsg1(){

        //1.
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject("http://localhost:8001/msg", String.class);
        log.info("response is -> {}",response);

        return response;
    }



    /**
     * 第二种方式(直接使用 restTemplate url通过loadBalancerClient 拼接))
     * @return
     */
    @GetMapping("/getProductMsg2")
    public String getProductMsg2(){
        ServiceInstance serviceInstance = loadBalancerClient.choose("PRODUCT");

        String url = String.format("http://%s:%s/msg",serviceInstance.getHost(),serviceInstance.getPort());
        log.info("this url is -> {}",url);
        String response = restTemplate.getForObject(url, String.class);
        log.info("response is -> {}",response);

        return response;
    }

    /**
     * 第三种方式(RestTemplateConfig 中配置 RestTemplate 并配合 @LoadBalanced 初始化)
     * @return
     */
    @GetMapping("/getProductMsg3")
    public String getProductMsg3(){

        String response = restTemplate.getForObject("http://PRODUCT/msg", String.class);
        log.info("response is -> {}",response);

        return response;
    }

    @GetMapping("/checkServer")
    public String checkServer(){



        return "the@health@is@good@";
    }



}
